const util = require('../../../../utils/util.js');
const api = require('../../../../config/api.js');
const recorderManager = wx.getRecorderManager();
var recordInterval = null;
const app = getApp();
Page({
  data: {
    type:'',
    index:'',
    time: '',//定时器
    imgInfo: {},
    openDelete: false,//删除框
    openBiaoji: false,//标记面板
    openLuyin: false,//录音面板
    openLuyinName: false,//录音名称面板
    openLuyining: false,//录音状态
    openTiezhi: false,//贴纸面板
    biaojiPanel: 0,//标记展示模块
    tiezhiPanel: 0,//标记展示模块
    showAddLj: false,//添加链接面板
    showAddLjName: false,//添加链接名称
    openError: false,//错误提示面板
    diaryAudio: {},//音频
    playAudio: false,//音频播放
    showDelLuyin: false,//删除音频提现面板
    ktDecalsList: ["https://image.xingqubaike.com:8443/minicard/ucenter/personhome/homesetup/tiezhizhu.png", "https://image.xingqubaike.com:8443/minicard/ucenter/personhome/homesetup/tiezhizhu.png", "https://image.xingqubaike.com:8443/minicard/ucenter/personhome/homesetup/tiezhizhu.png", "https://image.xingqubaike.com:8443/minicard/ucenter/personhome/homesetup/tiezhizhu.png", "https://image.xingqubaike.com:8443/minicard/ucenter/personhome/homesetup/tiezhizhu.png", "https://image.xingqubaike.com:8443/minicard/ucenter/personhome/homesetup/tiezhizhu.png", "https://image.xingqubaike.com:8443/minicard/ucenter/personhome/homesetup/tiezhizhu.png", "https://image.xingqubaike.com:8443/minicard/ucenter/personhome/homesetup/tiezhizhu.png",]
  },
  onLoad: function (option) {
    var _this = this; 
    _this.setData({
      logininfo: app.globalData.logininfo,
      openid: app.globalData.logininfo.openid, 
      userName: app.globalData.logininfo.userInfo.nickName
    });
    var info = JSON.parse(option.info)
    var type = option.type
    var index = option.index
    _this.setData({
      imgInfo: info,
      type: type,
      index: index
    })
    console.log(_this.data.imgInfo)
  },
  onReady: function (option){
    var _this = this
  },
  //打开标记面板
  showBiaoji: function(){
    var _this = this
    _this.setData({
      openBiaoji: true
    })
  },
  //选择标记展示面板
  selectBiaojiPanel: function (e) {
    var _this = this
    var index = e.currentTarget.dataset.index
    _this.setData({
      biaojiPanel: index
    })
  },
  //打开贴纸面板
  showTiezhi: function () {
    var _this = this
    var openTiezhi = _this.data.openTiezhi
    if (openTiezhi){
      _this.setData({
        openTiezhi: false
      })
    }else{
      _this.setData({
        openTiezhi: true
      })
    } 
  },
  //选择贴纸展示面板
  selectTiezhiPanel: function (e) {
    var _this = this
    var index = e.currentTarget.dataset.index
    _this.setData({
      tiezhiPanel: index
    })
  },
  //打开录音面板
  showLuyin: function () {
    var _this = this
    _this.setData({
      openLuyin: true
    })
  },
  //打开音频名字编辑
  openBianjiAudioName: function(){
    var _this = this
    _this.setData({
      openLuyinName: true,
    })
  },
  //打开删除音频面板
  openDelLuyin: function(){
    var _this = this
    _this.setData({
      showDelLuyin: true,
    })
  },
  //删除音频
  deleteAudio: function(){
    var _this = this
    wx.stopBackgroundAudio();//暂停正在播放音乐
    var info = _this.data.imgInfo
    info.luyin = ''
    _this.setData({
      imgInfo: info,
      luyinName: '',
    })
  },
  //开始录音
  beginLuyin: function(){
    var _this = this
    if (_this.data.imgInfo.luyin != null && _this.data.imgInfo.luyin != ''){
      wx.showToast({
        title: '已有音频标签',
        icon: "none",
        duration: 1500
      })
    }else{
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.record']) {
            wx.authorize({
              scope: 'scope.record',
              success() {
                _this.recorderStart();
                _this.setData({
                  openLuyining: true
                })
              },
              fail: function () {
                wx.showToast({
                  title: '无法获取麦克风',
                  icon: 'none',
                  duration: 1500
                })
              }
            })
          } else {
            _this.recorderStart();
            _this.setData({
              openLuyining: true
            })
          }
        }
      })
    }
  },
  //开始录音
  recorderStart: function () {
    var _this = this;
    const recorderOptions = {
      duration: util.getAudioFileMaxTime("diary"),//指定录音的时长，单位 ms
      format: 'mp3'
    }
    var diaryAudio = _this.data.diaryAudio;
    diaryAudio.state = "1";// 1正在录音  2录音完毕（state==2的时候，playState无效）
    diaryAudio.playState = "1";// 1正常录音  2暂停录音
    diaryAudio.totalTime = 0;
    diaryAudio.totalDate = "00:00";
    diaryAudio.isVoiceDialogShow = true;
    diaryAudio.isShow = true;
    _this.setData({
      diaryAudio: diaryAudio
    })
    //开始录音
    recorderManager.start(recorderOptions);
    // 定时器计算录音时间
    _this.doRecordInterval();
    // 录音结束
    recorderManager.onStop((res) => {
      _this.stopRecorderExecute(res);
    });
    // 录音中断
    recorderManager.onInterruptionBegin((res) => {
      recorderManager.stop();
      _this.setData({
        ["diaryAudio.isVoiceDialogShow"]: false
      })
      _this.stopRecorderExecute(res);
    });
  },
  //暂停录音
  pauseRecorder: function (e) {
    var _this = this;
    _this.setData({
      ["diaryAudio.playState"]: "2"
    });
    recorderManager.pause();
    _this.doClearInterval();
  },
  //继续录音
  resumeRecorder: function (e) {
    var _this = this;
    _this.setData({
      ["diaryAudio.playState"]: "1"
    })
    recorderManager.resume();
    _this.doRecordInterval();
  },
  //停止录音
  stopRecorder: function (e) {
    var _this = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      _this.stopRecorderExecute(res);
    });
  },
  //清空录音
  clearRecorder: function () {
    var _this = this;
    _this.doClearInterval();
    _this.setData({
      ["diaryAudio.isVoiceDialogShow"]: false
    })
    recorderManager.stop();
    setTimeout(function () {
      _this.beginLuyin();
    }, 100)
  },
  //停止录音后的业务代码
  stopRecorderExecute: function (tempFile) {
    var _this = this;
    _this.doClearInterval();
    var isVoiceDialogShow = _this.data.diaryAudio.isVoiceDialogShow;
    if (isVoiceDialogShow) {
      var totalTime = parseInt(tempFile.duration / 1000);
      var diaryAudio = _this.data.diaryAudio;
      diaryAudio.state = "2";
      diaryAudio.src = tempFile.tempFilePath;
      diaryAudio.title = "";
      diaryAudio.currentTime = 0;
      diaryAudio.totalTime = totalTime;
      diaryAudio.fileSize = tempFile.fileSize;
      diaryAudio.startDate = "00:00";
      diaryAudio.totalDate = util.digitalFormatTime(totalTime);
      diaryAudio.voiceBoFangImage = api.AudioNoBoFangImage_Name;
      _this.setData({
        diaryAudio: diaryAudio,
        openLuyin: false,
        openLuyinName: true,
      })
    }
  },
  //获取音频名字输入的文本
  inputLuyinName: function (e) {
    var _this = this
    var value = e.detail.value
    _this.setData({
      luyinName: value,
    })
  },
  //添加录音标记
  addLuyin: function () {
    var _this = this
    var diaryAudio = _this.data.diaryAudio
    var luyinName = _this.data.luyinName
    if (luyinName == '' || luyinName == null) {
      var luyinName = _this.data.userName + '的音频'
    }
    diaryAudio.title = luyinName;
    _this.setData({
      selType: "audio",
      diaryAudio: diaryAudio,
    })
    _this.addAddrBQ();
  },
  //开启音频播放
  showPlayAudio: function () {
    var _this = this
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    var playAudio = _this.data.playAudio
    if (playAudio) {
      backgroundAudioManager.pause();//暂停播放音乐
      wx.stopBackgroundAudio();//暂停正在播放音乐
      _this.setData({
        playAudio: false
      })
    } else {
      wx.stopBackgroundAudio();//暂停正在播放音乐
      backgroundAudioManager.startTime = 0;
      backgroundAudioManager.title = _this.data.imgInfo.luyin.title
      backgroundAudioManager.src = _this.data.imgInfo.luyin.src
      backgroundAudioManager.play();
      _this.setData({
        playAudio: true
      })
    }
  },
  //打开输入链接
  showAddLianjie: function(){
    var _this = this
    _this.setData({
      showAddLj: true,
      openBiaoji: false,
    })
  },
  //获取链接输入的文本
  inputLianjieiText: function (e) {
    var _this = this
    var value = e.detail.value
    _this.setData({
      lianjieiText: value,
    })
  },
  //效验链接文本
  albumInfoHrefBlur: function () {
    var _this = this;
    var value = _this.data.lianjieiText;
    if (value != '' && value != null) {
      var reg = /^https:\/\/mp.weixin.qq.com*/;
      if (value.length > 0 && !reg.test(value)) {
        _this.setData({
          openError: true,
          errorText: '该内容不是公众号文章链接，请重新操作！',
          lianjieiText: '',
        })
      } else {
        _this.setData({
          selLianjie: value,
          showAddLj: false,
          showAddLjName: true,
        })
      }
    }
  },
  //获取链接名字输入的文本
  inputLianjieName: function (e) {
    var _this = this
    var value = e.detail.value
    _this.setData({
      lianjieiName: value,
    })
  },
  //添加链接标记
  addLianjie: function () {
    var _this = this
    var lianjieiText = _this.data.lianjieiText
    var lianjieiName = _this.data.lianjieiName
    if (lianjieiName == '' || lianjieiName == null) {
      var lianjieiName = '公众号文章'
    }
    var selLianjieiText = lianjieiText
    var selLianjieiName = lianjieiName
    _this.setData({
      selType: "lianjie",
      selLianjieiText: selLianjieiText,
      selLianjieiName: selLianjieiName,
      lianjieiText: '',
      lianjieiName: '',
    })
    _this.addAddrBQ();
  },
  //打开输入文本
  showAddText: function () {
    var _this = this
    _this.setData({
      showAddText: true,
      openBiaoji: false,
    })
  },
  //获取文本标记输入的文本
  inputTextBiaoji: function (e) {
    var _this = this
    var value = e.detail.value
    _this.setData({
      textBiaoji: value,
    })
  },
  //添加文本标记
  addText: function () {
    var _this = this
    var textBiaoji = _this.data.textBiaoji.replace(/\s+/g, '')
    if (textBiaoji == '' || textBiaoji == null) {
      _this.setData({
        textBiaoji: '',
        showAddText: false,
      })
      wx.showToast({
        title: '内容不能为空',
        icon: 'none',
        duration: 1500
      })
    }else{
      var selTextBiaoji = textBiaoji
      _this.setData({
        selType: "text",
        selTextBiaoji: selTextBiaoji,
        textBiaoji: '',
      })
      _this.addAddrBQ();
    }
  },
  //打开选择地址组件
  openAddrPicker: function () {
    var _this = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              _this.albumInfoPositionStart();
            },
            fail: function () {
            }
          })
        } else {
          _this.albumInfoPositionStart();
        }
      }
    })
  },
  albumInfoPositionStart: function () {
    var _this = this;
    wx.chooseLocation({
      success: function (res) {
        var value = res.name;
        var latitude = res.latitude;
        var longitude = res.longitude;
        var address = res.address;
        if (value != null && value.length > 0) {
          _this.setData({
            selType: "addr",
            selAddr : value,
            selAddrLatitude : latitude,
            selAddrLongitude : longitude,
            selAddress : address,
          })
          _this.addAddrBQ();
        } else {
          util.dialogAlert("未选中有效地址")
        }
      }
    })
  },
  //选择地址标记
  selectaddr: function (e) {
    var _this = this
    var addr = e.currentTarget.dataset.addr
    var latitude = e.currentTarget.dataset.latitude
    var longitude = e.currentTarget.dataset.longitude
    var address = e.currentTarget.dataset.address
    _this.setData({
      selType: "addr",
      selAddr: addr,
      selAddrLatitude: latitude,
      selAddrLongitude: longitude,
      selAddress: address,
    })
    _this.addAddrBQ();
  },
  //选择圈子标记
  selectcircle: function(e) {
    var _this = this
    var selTitle = e.currentTarget.dataset.title
    var selCircleid = e.currentTarget.dataset.circleid
    _this.setData({
      selType: "circle",
      selTitle: selTitle,
      selCircleid: selCircleid,
    })
    _this.addAddrBQ();
  },
  //选择贴纸
  selectTiezhi: function (e) {
    var _this = this
    var info = _this.data.imgInfo
    var index = e.currentTarget.dataset.index
    var type = _this.data.tiezhiPanel
    if (type == 0) {
      var arr = _this.data.ktDecalsList
      var selImg = arr[index]
    }
    if (type == 1) {

    }
    if (type == 2) {

    }
    if (type == 3) {

    }
    if (type == 4) {

    }
    _this.setData({
      selType: "decal",
      selImg: selImg,
    })
    _this.addAddrBQ();
  },
  //将选中的标记数据加入标签
  addAddrBQ: function(){
    var _this = this
    var info = _this.data.imgInfo
    var selType = _this.data.selType
    //地址
    if (selType=="addr"){
      var selAddr = _this.data.selAddr
      var selAddrLatitude = _this.data.selAddrLatitude
      var selAddrLongitude = _this.data.selAddrLongitude
      var selAddress = _this.data.selAddress
      info.tags.push({ "type": 0, "addr": selAddr, "latitude": selAddrLatitude, "longitude": selAddrLongitude, "address": selAddress, "top": 180, "left": 150, "rotate": 0, "show": true})
    }
    //圈子
    if (selType == "circle"){
      var selTitle = _this.data.selTitle
      var selCircleid = _this.data.selCircleid
      info.tags.push({ "type": 1, "title": selTitle, "circleid": selCircleid, "top": 180, "left": 150, "rotate": 0, "show": true})
    }
    //宝贝
    if (selType == 2) {

    }
    //店铺
    if (selType == 3) {

    }
    //链接
    if (selType == "lianjie") {
      var selLianjieiText = _this.data.selLianjieiText
      var selLianjieiName = _this.data.selLianjieiName
      info.tags.push({ "type": 4, "linkName": selLianjieiName, "linkSrc": selLianjieiText, "top": 180, "left": 150, "rotate": 0,"show": true})
    }
    //文字
    if (selType == "text") {
      var selTextBiaoji = _this.data.selTextBiaoji
      info.tags.push({ "type": 5, "text": selTextBiaoji, "top": 180, "left": 150, "rotate": 0,"show": true})
    }
    //音频
    if (selType == "audio"){
      var diaryAudio = _this.data.diaryAudio
      info.luyin = diaryAudio
    }
    //贴纸
    if (selType == "decal") {
      var selImg = _this.data.selImg
      info.decals.push({ "src": selImg, "top": 162, "left": 162, "show": true })
    }
    _this.setData({
      imgInfo: info
    })
    console.log(info)
    _this.delSelData();
    _this.closeMC();
  },
  //清空标记数据
  delSelData: function(){
    var _this = this
    _this.setData({
      selType: null,
      //清空地址标记数据
      selAddr: '',
      selAddrLatitude: '',
      selAddrLongitude: '',
      selAddress: '',
      //清空圈子标记数据
      selTitle: '',
      selCircleid: '',
      //清空链接标记数据
      selLianjieiText: '',
      selLianjieiName: '',
      //清空文字标记数据
      selTextBiaoji: '',
      //清空贴纸数据
      selImg: '',
    })
  },
  //标记块拖动点击开始
  biaojiStartMove: function (e) {
    var _this = this
    var info = _this.data.imgInfo
    var tagIndex = e.currentTarget.dataset.index
    var startX = e.changedTouches[0].clientX
    var startY = e.changedTouches[0].clientY
    info.tags[tagIndex].startX = startX
    info.tags[tagIndex].startY = startY
    _this.setData({
      imgInfo: info,
      openDelete: true
    })
  },
  //标记块拖动点击结束
  biaojiEndMove: function (e) {
    var _this = this
    var info = _this.data.imgInfo
    var tagIndex = e.currentTarget.dataset.index
    //防止标记删除后手指未松开继续移动报错
    if (info.tags[tagIndex] != '' && info.tags[tagIndex] != null) {
      var startX = info.tags[tagIndex].startX
      var startY = info.tags[tagIndex].startY
      var endX = e.changedTouches[0].clientX
      var endY = e.changedTouches[0].clientY
      info.tags[tagIndex].left += parseInt(endX - startX)
      info.tags[tagIndex].top += parseInt(endY - startY)
      info.tags[tagIndex].startX = endX
      info.tags[tagIndex].startY = endY
      //出画面删除
      if (info.tags[tagIndex].top > 370) {
        info.tags[tagIndex].show = false
      }
      _this.setData({
        imgInfo: info,
      })
    }
    _this.doneMove();
  },
  //贴纸块拖动开始
  decalsStartMove: function(e){
    var _this = this
    var info = _this.data.imgInfo
    var index = e.currentTarget.dataset.index
    var startX = e.changedTouches[0].clientX
    var startY = e.changedTouches[0].clientY
    info.decals[index].startX = startX
    info.decals[index].startY = startY
    _this.setData({
      imgInfo: info,
      openDelete: true
    })
  },
  //贴纸块拖动点击结束
  decalsEndMove: function (e) {
    var _this = this
    var info = _this.data.imgInfo
    var index = e.currentTarget.dataset.index
    //防止标记删除后手指未松开继续移动报错
    if (info.decals[index] != '' && info.decals[index] != null) {
      var startX = info.decals[index].startX
      var startY = info.decals[index].startY
      var endX = e.changedTouches[0].clientX
      var endY = e.changedTouches[0].clientY
      info.decals[index].left += parseInt(endX - startX)
      info.decals[index].top += parseInt(endY - startY)
      info.decals[index].startX = endX
      info.decals[index].startY = endY
      //出画面删除
      if (info.decals[index].top > 340) {
        info.decals[index].show = false
      }
      _this.setData({
        imgInfo: info,
      })
    }
    _this.doneMove();
  },
  //关闭删除框
  doneMove: function(){
    var _this = this
    clearInterval(_this.data.time);
    var time = setTimeout(function(){
      _this.setData({
        openDelete: false,
      })
    },2000)
    _this.setData({
      time: time
    })
  },
  //翻转标记
  bioajiRotate: function (e) {
    var _this = this
    var info = _this.data.imgInfo
    var tagIndex = e.currentTarget.dataset.index
    if (info.tags[tagIndex].rotate==180){
      info.tags[tagIndex].rotate = 0
    }else{
      info.tags[tagIndex].rotate = 180
    }
    _this.setData({
      imgInfo: info
    })
  },
  //定时器计算录音时间
  doRecordInterval: function () {
    var _this = this;
    if (recordInterval == null) {
      recordInterval = setInterval(function () {
        var diaryAudio = _this.data.diaryAudio;
        var totalTime = diaryAudio.totalTime + 1;
        var totalDate = util.digitalFormatTime(totalTime);
        _this.setData({
          ["diaryAudio.totalTime"]: totalTime,
          ["diaryAudio.totalDate"]: totalDate
        });
      }, 1000);
    }
  },
  //清除定时器
  doClearInterval: function () {
    clearInterval(recordInterval);
    recordInterval = null;
  },
  //获取搜索的文字
  inputText: function (e) {
    var _this = this
    var value = e.detail.value
    _this.setData({
      searchText: value,
    })
  },
  //关闭面板
  closeMC:function(){
    var _this = this
    _this.setData({
      openBiaoji: false,
      openTiezhi: false,
      openLuyin: false,
      showAddLj: false,
      showAddText: false,
      showAddLjName: false,
      openLuyining: false,
      openLuyinName:false,
      showDelLuyin: false
    })
    _this.doClearInterval();
  },
  //关闭错误提示
  closeError: function(){
    var _this = this
    _this.setData({
      openError: false,
    })
  },
  //下一步
  next:function(){
    var _this = this
    var info = _this.data.imgInfo
    var type = _this.data.type
    if (type =="again"){
      var index = _this.data.index
      app.journey.imageList[index] = info
    }else{
      app.journey.imageList.push(info);
    }
    console.log(app.journey.imageList)
    wx.redirectTo({
      url: 'publishJourney/publishJourney',
    })
  },
})